
package combat.example.client;

import gnu.cajo.utils.extra.TransparentItemProxy;

import java.util.ArrayList;

import combat.example.protocol.data.ChatEntry;
import combat.example.protocol.interfaces.ChatInt;
import combat.example.protocol.interfaces.SimulationInt;


/**
 * @author Laurens Andriessen
 * @version 1.0
 */
public class ClientApplication {

	public static void main(String[] args) {
		int myUserID = -1;

		SimulationInt sim = null;

		// Simulation (single, static instance)
		try {
			// SimulationInt sim = (SimulationInt) TransparentItemProxy.getItem(
			// "//localhost:28000/Simulation", new Class[] { SimulationInt.class
			// });

			// Log in onto the server
			// TODO make-it-work: complete
			// server.protcol.implementation.Simulation
			// myUserID = sim.userLogOn("Selie, Peter");
			// Example-fix
			myUserID = 0;
			// if (myUserID == -1) throw new Exception();

		} catch (Exception e) {
			System.out.println("Error! Something went wrong under //Simulation");
			e.printStackTrace();
		}

		// Chat (single, static instance)
		String chatHash = "";
		ArrayList<ChatEntry> chats = null;
		try {
			for (int i = 0; i < 2; i++) {
				ChatInt chatServer = (ChatInt) TransparentItemProxy.getItem(
						"//localhost:28000/Chat", new Class[] { ChatInt.class });
				// Will you join the tea party? Sending a chat
				// userID: -1 = only when operator sends the chat
				// userID: myUserID
				// For the targetID (2nd parameter) there are three different
				// options:
				// targetID: -1 = if client: entire team, if operator: global
				// targetID: 0 = userID=0, 1 = userID=1, 2 = userID=2...etc.
				if (i == 1) chatServer.sendChat(myUserID, -1, "Howdy!");

				// Get the chat hash and compare it to the chatHash stored
				// locally
				// If they are not equal, then get all chats from the server
				String newChatHash = chatServer.getChatHash().toString();
				if (chatHash != newChatHash) {
					chatHash = newChatHash;
					System.out.println("ChatHashes not equal!");

					chats = chatServer.getChats();
					// List chat messages
					for (ChatEntry msg : chats) {
						System.out.println("ClientID: " + msg.getUserID());
						System.out.println("TargetID: " + msg.getTargetID());
						System.out.println("Timestamp: " + msg.getTimestamp().toString());
						System.out.println("[Message] " + msg.getMessage());
						System.out.println("------------");
					}
				} else System.out.println("ChatHashes equal!");
			}
		} catch (Exception e) {
			System.out.println("Error! Something went wrong under //Chat");
			e.printStackTrace();
		}

	}
}
